package cn.jy.careuplusdoctor.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import cn.jy.careuplusdoctor.utils.ProgressMultipartEntity.ProgressCallback;


public class HttpUtil{

	public static final String CHAR_SET = "GB2312";
	
	public static Bitmap loadImage(final String url){
		URL u = null;  
        Bitmap bitmap = null;  
        try {  
        	u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();  
            conn.setDoInput(true);  
            conn.connect();  
            InputStream is = conn.getInputStream();  
            bitmap = BitmapFactory.decodeStream(is);  
            is.close();  
            conn.disconnect();
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return bitmap;
	}
	
	public static String loadTextByMultipart(String url,List<Param> params){
		return loadTextByMultipart(url, params, null);
	}
	
	public static String loadTextByMultipart(String url,List<Param> params,final ProgressCallback progressCallback){
		if(!StringUtil.isNotEmpty(url)){
			return "";
		}
		StringBuilder rst = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		// 设置通信协议版本
		client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

		HttpPost httppost = new HttpPost(url);
		
		ProgressMultipartEntity multipartEntity = new ProgressMultipartEntity();
		try {
			if(params!=null){
				Param param;
				for(int i = 0; i < params.size(); i++){
					param = params.get(i);
					if(param.getValue() instanceof File){
						File file = (File) param.getValue();
						if(file.isFile()){
							multipartEntity.addPart(param.getKey(), new FileBody((File)param.getValue()));
						}
					}else{
						multipartEntity.addPart(param.getKey(), new StringBody(StringUtil.parseString(param.getValue()),Charset.forName("GBK")));
					}
				}
			}
			final long _totalSize = multipartEntity.getContentLength();
			if(progressCallback!=null){
				ProgressCallback _progressCallback = new ProgressCallback() {
					@Override
					public void progress(long percentage) {
						progressCallback.progress((int) ((percentage / (float) _totalSize) * 100));
					}
				};
				multipartEntity.setProgressCallback(_progressCallback);
			}
			httppost.setEntity(multipartEntity);
			HttpResponse response;
			response = client.execute(httppost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if(statusCode==200){
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,CHAR_SET));
				String line;
				while((line=reader.readLine())!=null){
					rst.append(line);
				}
				is.close();
			}
			client.getConnectionManager().shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return rst.toString();
	}
	
	public static String loadText(String url,List<BasicNameValuePair> params) throws UnsupportedEncodingException{
		if(!StringUtil.isNotEmpty(url)){
			return "";
		}
		StringBuilder rst = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		if(params!=null){
			httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
		}
		try{
			HttpResponse response = client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if(statusCode==200){
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,CHAR_SET));
				String line;
				while((line=reader.readLine())!=null){
					rst.append(line);
				}
				is.close();
			}
			client.getConnectionManager().shutdown();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return rst.toString();
	}
	
	public static String loadText(String url) throws UnsupportedEncodingException{
		return loadText(url, null);
	}
	
	public static JSONArray loadArray(String url) throws JSONException, UnsupportedEncodingException{
		return loadArray(url,null);
	}
	
	public static JSONArray loadArray(String url,List<BasicNameValuePair> params) throws JSONException, UnsupportedEncodingException{
		String jsonStr = loadText(url,params);
		JSONArray jsonArray = new JSONArray(jsonStr);
		return jsonArray;
	}
	
	public static JSONObject loadJson(String url,List<BasicNameValuePair> params) throws JSONException, UnsupportedEncodingException{
		String jsonStr = loadText(url,params);
		JSONObject jsonObject = new JSONObject(jsonStr);
		return jsonObject;
	}
	
	public static JSONObject loadJson(String url) throws JSONException, UnsupportedEncodingException{
		return loadJson(url, null);
	}
}